var text = ``;
window.onload = function () {
  chrome.storage.local.get("text", (data) => {
    if (data.text) {
      text = data.text;
    }
  });
};

/* eslint-disable no-unused-vars */
window.onload = function () {
  chrome.storage.local.get("isRunning", (data) => {
    if (data.isRunning) {
      var random = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
      var T = setTimeout(() => {
        clearTimeout(T);
        startProgram();
      }, random);
    }
  });
};

function startProgram() {
  var chatBtn = document.querySelector(".btn .btn-startchat");
  // 测试代码start
  // setTimeout(() => {
  //   // 关闭当前聊天窗口;
  //   chrome.storage.local.set({ runningOneStatus: "done" });
  //   // window.close();
  //   chrome.runtime.sendMessage({ action: "close_current_tab" });
  // }, 0);
  // return;
  // 测试代码end
  console.log("debugger");
  chatBtn.click();
  // if (chatBtn.innerText === "继续沟通") {
  //   chatBtn.click();
  // } else {
  //   chatBtn.click();
  // observePopup();
  // }
  observePopup();
}

function observePopup() {
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === "childList") {
        const popupBtn = document.querySelector(".btn.btn-sure");
        if (popupBtn && popupBtn.innerHTML === "确定") {
          // 今日投递已达上限
          chrome.storage.local.set({
            isRunning: false,
          });
          return;
        }
        if (popupBtn) {
          popupBtn.click();
          observer.disconnect(); // 停止观察
        }
      }
    });

    const chatInput = document.querySelector(".input-area"); // 修改为实际 class
    const sendButton = document.querySelector(".send-message"); // 修改为实际 class
    if (chatInput && sendButton) {
      setTimeout(() => {
        chatInput.value = text;
        chatInput.dispatchEvent(new Event("input", { bubbles: true }));
        setTimeout(() => {
          sendButton.click();
          setTimeout(() => {
            // 关闭当前聊天窗口;
            chrome.storage.local.set({ runningOneStatus: "done" });
            // window.close();
            chrome.runtime.sendMessage({ action: "close_current_tab" });
          }, 500);
        }, 500);
      }, 500);
      observer.disconnect(); // 只执行一次，避免重复触发
    }
  });

  // 配置观察选项
  const config = { childList: true, subtree: true };
  // 开始观察目标节点
  observer.observe(document.body, config);
}
